package com.cyf.smartCity.service.impl;

import com.cyf.db.bean.LocalCarWarning;
import com.cyf.db.mapper.smartCity.LocalCarWarningMapper;
import com.cyf.smartCity.bean.SendData;
import com.cyf.smartCity.service.LocalCarWarningService;
import com.cyf.smartCity.service.SendDataService;
import com.cyf.util.CommonRsp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author hfy
 * @date 2018/12/10
 */
@Service
public class LocalCarWarningServiceImpl implements LocalCarWarningService {

    @Autowired
    private LocalCarWarningMapper carWarningMapper;
    @Autowired
    private SendDataService sendDataService;

    @Override
    public CommonRsp addWarningCar(LocalCarWarning carWarning) {
        if (checkPlateExist(carWarning.getLicense(), carWarning.getParkingId())) {
            return CommonRsp.fail("该车牌号已添加！");
        }
        carWarningMapper.insert(carWarning);
        sendDataService.insert(LocalCarWarning.class, carWarning.getId(), null,
                carWarning.getParkingId(), SendData.OPT_TYPE_INSERT);
        return CommonRsp.ok();
    }

    private boolean checkPlateExist(String license, Integer parkingId) {
        Integer count = carWarningMapper.countByLicenseAndParkingId(license, parkingId);
        return count != null && count > 0;
    }

    @Override
    public CommonRsp editWarningCar(Integer id, String plate) {
        LocalCarWarning carWarning = carWarningMapper.getById(id);
        if (carWarning == null) {
            return CommonRsp.fail("查找信息失败！");
        }
        if (carWarning.getLicense().equals(plate)) {
            return CommonRsp.ok();
        }
        if (checkPlateExist(plate, carWarning.getParkingId())) {
            return CommonRsp.fail("该车牌号已添加！");
        }
        carWarningMapper.update(id, plate);
        sendDataService.insert(LocalCarWarning.class, carWarning.getId(), carWarning.getLocalCarwarningId(),
                carWarning.getParkingId(), SendData.OPT_TYPE_UPDATE);
        return CommonRsp.ok();
    }

    @Override
    public void deleteById(Integer id) {
        LocalCarWarning carWarning = carWarningMapper.getById(id);
        if (carWarning == null) {
            return;
        }
        carWarningMapper.logicDeleteById(id);
        sendDataService.insert(LocalCarWarning.class, id, carWarning.getLocalCarwarningId(),
                carWarning.getParkingId(), SendData.OPT_TYPE_DELETE);
    }
}
